<template>
  <t-modal
    :title="operateType == 1 ? '新增' : '编辑'"
    width="900px"
    :visible="visible"
    @ok="onSubmit()"
    @cancel="closeModal()"
    wrapClassName="add-modal-container"
    forceRender
  >
    <div class="curve-modal-body">
      <a-form-model ref="ruleForm" :model="form" :rules="rules">
        <a-form-model-item label="名称" prop="name">
          <a-input v-model="form.name" placeholder="请输入名称"></a-input>
        </a-form-model-item>
        <a-form-model-item
          label="流程图"
          prop="images"
          :rules="{
            required: true,
            message: '请选择流程图',
          }"
        >
          <bjUploadImg
            :count="1"
            v-model="form.images"
            @change="upLoadImage($event)"
            replaceField="url"
          ></bjUploadImg>
        </a-form-model-item>
        <a-form-model-item
          label="流程图原件"
          prop="files"
          :rules="{
            required: true,
            message: '请选择流程图原件',
          }"
        >
          <bjUploadFile
            :count="1"
            v-model="form.files"
            @download="downloadFile($event)"
            @change="upLoadFileChange($event)"
            @preview="viewFile($event)"
            :replaceFields="{
              fileName: 'fileName',
              fileSize: 'fileSize',
              fileType: 'fileType',
            }"
            type="all"
          ></bjUploadFile>
        </a-form-model-item>
        <a-form-model-item label="上传人">
          <a-input v-model="form.creator" disabled></a-input>
        </a-form-model-item>
        <a-form-model-item label="上传时间">
          <a-input v-model="form.creatorTime" disabled></a-input>
        </a-form-model-item>
      </a-form-model>
    </div>
    <!-- 附件预览弹窗 -->
    <previewModal
      ref="previewModal"
      :visible.sync="previewModal.visible"
      :loading="previewModal.loading"
    ></previewModal>
  </t-modal>
</template>

<script>
import { axios } from "@/utils/request";
import { getNowDateStr } from "@/utils/util";
import { downloadDfs, getToken } from "@/utils/TopVUI";
import { mapGetters } from "vuex";
//上传图片
import bjUploadImg from "@/components/extendCustom/bj-upload-img";
//文件
import bjUploadFile from "@/components/extendCustom/bj-upload-file";
//预览
import previewModal from "@/pages/document/minio/previewModal";
import { saveFlowPath, detailFlowPath } from "@/api/knowledgeBase";
export default {
  components: {
    bjUploadImg,
    bjUploadFile,
    previewModal,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    parameter: {
      type: Object,
      default: () => {
        return {};
      },
    },
    operateType: {
      type: [String, Number],
      default: "",
    },
  },
  data() {
    return {
      form: {
        //名称
        name: "",
        //原件
        files: [],
        //流程图
        images: [],
        //创建人
        creator: "",
        //创建时间
        creatorTime: "",
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入名称",
          },
        ],
      },
      //预览
      previewModal: {
        visible: false,
        loading: false,
      },
    };
  },
  computed: {
    ...mapGetters(["nickname", "configData"]),
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          let { operateType } = this;
          if (operateType == 1) {
            this.form.creator = this.nickname;
            this.form.creatorTime = getNowDateStr(1);
          } else {
            this.getDetail();
          }
        }
      },
      immediate: true,
    },
  },
  methods: {
    //预览
    viewFile(file) {
      let { url } = file;
      this.previewModal.loading = true;
      this.$refs.previewModal.type = "file";
      this.$refs.previewModal.fileUrl =
        this.kkFileView +
        "/onlinePreview?url=" +
        encodeURIComponent(Base64.encode(url)) +
        "&watermarkTxt=" +
        //水印内容
        encodeURIComponent("") +
        "&token=" +
        getToken();

      this.previewModal.visible = true;
      this.previewModal.loading = false;
    },
    //下载
    downloadFile(row) {
      let { url } = row;
      if (!url) {
        this.$message.success("文件不存在", 1.5);
        return;
      }
      downloadDfs(url);
    },
    getDetail() {
      let { uuid } = this.parameter;
      detailFlowPath({ uuid })
        .then((res) => {
          this.form = {
            name: res.name,
            files: JSON.parse(res?.files ?? "[]"),
            images: JSON.parse(res?.images ?? "[]"),
            creator: res.creator,
            creatorTime: res.createTime,
          };
        })
        .catch((_) => {});
    },

    //提交
    onSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let { name, images, files } = this.form;
          //流程图
          const imageList = images.map(
            ({ $$DataType, file, loading, ...keepAttrs }) => keepAttrs
          );
          //原件
          const fileList = files.map(
            ({ $$DataType, file, loading, ...keepAttrs }) => keepAttrs
          );

          let formJson = {
            name: name,
            images: JSON.stringify(imageList),
            files: JSON.stringify(fileList),
          };

          //编辑
          if (this.parameter.uuid) {
            formJson.uuid = this.parameter.uuid;
          }
          saveFlowPath(formJson)
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                this.$message.success("操作成功", 1.5);
                this.$parent.getTreeData();
                this.closeModal();
              } else {
                this.$message.error(res?.message ?? "操作失败");
              }
            })
            .catch();
        }
      });
    },

    //上传图片
    upLoadImage({ file, index }) {
      let formData = new FormData();
      formData.append("bucket", "yx-cloud-vue");
      formData.append("file", file);
      this.$set(this.form["images"][index], "loading", true);
      axios
        .post(`/document/minio/uploadfile`, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          this.$set(this.form["images"][index], "bucket", res.bucket);
          this.$set(this.form["images"][index], "uid", res.dfsFileUuid);
          this.$set(this.form["images"][index], "docSize", res.docSize);
          this.$set(this.form["images"][index], "message", res.message);
          this.$set(this.form["images"][index], "object", res.object);
          this.$set(this.form["images"][index], "statusCode", res.statusCode);
          this.$set(this.form["images"][index], "title", res.title);
          this.$set(this.form["images"][index], "url", res.url);
        })
        .catch((_) => {
          this.$set(this.form["images"][index], "fail", true);
        })
        .finally((_) => {
          this.$set(this.form["images"][index], "loading", false);
        });
    },
    //上传文件
    upLoadFileChange({ file, index }) {
      let formData = new FormData();
      formData.append("bucket", "yx-cloud-vue");
      formData.append("file", file);
      this.$set(this.form["files"][index], "loading", true);
      axios
        .post(`/document/minio/uploadfile`, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          this.$set(this.form["files"][index], "uid", res.dfsFileUuid);
          this.$set(this.form["files"][index], "url", res.url);
        })
        .catch((_) => {
          this.$set(this.form["files"][index], "fail", true);
        })
        .finally((_) => {
          this.$set(this.form["files"][index], "loading", false);
        });
    },

    resetForm() {
      this.form = {
        //名称
        name: "",
        //流程图
        images: [],
        //原件
        files: [],
        //创建人
        creator: "",
        //创建时间
        creatorTime: "",
      };
      this.$refs.ruleForm.resetFields();
    },
    //关闭
    closeModal() {
      this.resetForm();
      this.$emit("update:visible", false);
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.add-modal-container {
  .ant-modal-body {
    padding: 0 !important;
  }
  .curve-modal-body {
    padding: 14px;
    box-sizing: border-box;
    max-height: 700px;
    overflow: hidden;
    overflow-y: auto;
    .ant-form-item {
      display: flex;
      .ant-form-item-label {
        flex-shrink: 0;
        width: 100px;
        white-space: pre-wrap;
        display: flex;
        justify-content: flex-end;
        line-height: 20px;
        margin-right: 2px;
        align-items: center;
        height: 36px;
      }
      .ant-form-item-control-wrapper {
        flex: 1;
        overflow: hidden;
      }
    }
    .bj-upload-file {
      .choosed-file-warp {
        width: 100%;
      }
    }
  }
}
</style>
